package mylab.starters.oss.config.aliyun;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import lombok.RequiredArgsConstructor;
import mylab.starters.oss.OssRule;
import mylab.starters.oss.config.OssAutoConfiguration;
import mylab.starters.oss.config.OssProperties;
import mylab.starters.oss.support.aliyun.AliyunOssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@AutoConfigureAfter(OssAutoConfiguration.class)
@ConditionalOnProperty(value = AliyunAutoConfiguration.PREFIX, havingValue = "true")
public class AliyunAutoConfiguration {

    static final public String PREFIX = OssProperties.PREFIX + ".aliyun.enabled";

    final private OssProperties ossProperties;

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnMissingBean
    public OSSClient ossClient() {
        OssProperties.AliyunOssProperties aliyun = ossProperties.getAliyun();

        // 创建ClientConfiguration。ClientConfiguration是OSSClient的配置类，可配置代理、连接超时、最大连接数等参数。
        ClientBuilderConfiguration config = new ClientBuilderConfiguration();
        // 设置OSSClient允许打开的最大HTTP连接数，默认为1024个。
        config.setMaxConnections(1024);
        // 设置Socket层传输数据的超时时间，默认为50000毫秒。
        config.setSocketTimeout(50000);
        // 设置建立连接的超时时间，默认为50000毫秒。
        config.setConnectionTimeout(50000);
        // 设置从连接池中获取连接的超时时间（单位：毫秒），默认不超时。
        config.setConnectionRequestTimeout(1000);
        // 设置连接空闲超时时间。超时则关闭连接，默认为60000毫秒。
        config.setIdleConnectionTime(60000);
        // 设置失败请求重试次数，默认为3次。
        config.setMaxErrorRetry(5);
        // 配置协议
        config.setProtocol(aliyun.getHttps() ? Protocol.HTTPS : Protocol.HTTP);

        return (OSSClient) new OSSClientBuilder().build(
                aliyun.getEndpoint(),
                aliyun.getAccessKey(),
                aliyun.getSecretKey(),
                config);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({OSSClient.class, OssRule.class})
    public AliyunOssTemplate aliossTemplate(OSSClient ossClient, OssRule ossRule) {
        return new AliyunOssTemplate(ossProperties.getAliyun(), ossRule, ossClient);
    }
}
